<template>
  <div v-loading="loading" element-loading-text="加载中..." class="order_type">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addOrderTypeDialogVisible = true">添加分类</HPlainButton>
        <el-dropdown trigger="click">
          <HButton>
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="name"
          placeholder="名称搜索"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table">
      <el-table
        ref="tableDom"
        border
        stripe
        resizable
        :data="tableData"
        row-key="id"
        :tree-props="{ children: 'childTypes' }"
        height="100%"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="40" fixed="left" :align="'center'" />
        <el-table-column
          show-overflow-tooltip
          type="index"
          :index="indexMethod"
          label="序号"
          width="60"
          fixed="left"
          :align="'center'"
        />
        <el-table-column show-overflow-tooltip prop="name" label="分类名称" min-width="150" />
        <el-table-column show-overflow-tooltip prop="sort" label="排序" width="70" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="150" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="150" />
        <el-table-column prop="status" label="状态" width="70" fixed="right" :align="'center'">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="!scope.row.status">启用</HStatus>
              <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="155">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink v-if="scope.row.level != 3" @click="addChild(scope.row)">添加子类</HLink>
              <HLink @click="editData(scope.row)">编辑</HLink>
              <h-link type="error" @click="handleDelOrderType(scope.row)">删除</h-link>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>

    <!-- 添加/编辑  分类弹窗 -->
    <h-dialog v-model="addDialog" :title="dialogTitle" :loading="dialogLoading">
      <el-form
        ref="formRef"
        label-position="top"
        inline-message
        class="modal_form_content"
        :rules="rules"
        :model="form"
      >
        <el-form-item v-if="dialogTitle == '添加下级'" label="父级名称" class="form-item" required>
          <el-input
            v-model.trim="form.parentId"
            clearable
            placeholder="请输入名称"
            :disabled="dialogTitle == '添加下级'"
          />
        </el-form-item>
        <el-form-item label="分类名称" class="form-item" prop="name">
          <el-input v-model.trim="form.name" clearable placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="分类排序" class="form-item" prop="sort">
          <el-input v-model.trim="form.sort" clearable placeholder="请输入大小" />
        </el-form-item>
        <el-form-item label="分类状态" class="same_line">
          <el-radio-group v-model="form.status">
            <el-radio :value="false" size="small">启用</el-radio>
            <el-radio :value="true" size="small">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="addDialog = false">取消</HButton>
      </template>
    </h-dialog>

    <AddOrderType
      v-model:visible="addOrderTypeDialogVisible"
      type="order"
      :other-param="{ orderModuleId: route.params.id as string }"
      @update="getList"
    />

    <AddChildOrderType
      v-model:visible="addOrderChildTypeDialogVisible"
      type="order"
      :order-module-id="(route.params.id as string)"
      :parent-type="currentAddChildOrderType"
      @update="getList"
    />

    <UpdateOrderType
      v-model:visible="currentUpdateTypeDialogVisible"
      type="order"
      :update-type="currentUpdateOrderType"
      @update="getList"
    />
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, reactive, h } from 'vue'
  import { useRoute } from 'vue-router'
  import { Search, Warning, Delete, CircleCheck, ArrowDown } from '@element-plus/icons-vue'
  import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, TableInstance } from 'element-plus'
  import {
    moduleTypeSave,
    moduleTypeGetList,
    moduleTypeDisable,
    moduleTypeDelete,
  } from '@/api/basic'
  import { OrderType } from './types'
  import AddOrderType from '@/components/pages/common/type/add-type/AddType.vue'
  import UpdateOrderType from '@/components/pages/common/type/update-type/UpdateType.vue'
  import AddChildOrderType from '@/components/pages/common/type/add-child-type/AddChildType.vue'

  // 添加分类弹窗显示状态
  const addOrderTypeDialogVisible = ref(false)

  // 添加子类弹窗显示状态
  const addOrderChildTypeDialogVisible = ref(false)

  // 编辑分类弹窗显示状态
  const currentUpdateTypeDialogVisible = ref(false)

  // 当前正在添加子类的分类
  const currentAddChildOrderType = ref({
    id: '',
    name: '',
    parentId: '',
    status: false,
    sort: 0,
    childData: [],
    level: 1,
  })

  // 当前正在编辑的分类
  const currentUpdateOrderType = ref({
    id: '',
    name: '',
    parentId: '',
    status: false,
    sort: 0,
    level: 1,
  })

  /**
   * 添加下级
   * @param {Object} obj - 添加子类的分类
   */
  const addChild = (obj) => {
    currentAddChildOrderType.value = {
      id: obj.id,
      name: obj.name,
      sort: obj.sort,
      status: obj.status,
      parentId: obj.parentId,
      level: obj.level,
      childData: [],
    }
    addOrderChildTypeDialogVisible.value = true
  }

  /**
   * 编辑分类
   * @param {Object} obj - 正在编辑的分类
   */
  const editData = (obj) => {
    currentUpdateOrderType.value = {
      id: obj.id,
      name: obj.name,
      sort: obj.sort,
      status: obj.status,
      parentId: obj.parentId,
      level: obj.level,
    }
    currentUpdateTypeDialogVisible.value = true
  }

  const handleDelOrderType = (orderType: OrderType) => {
    if (tableDom.value) {
      tableDom.value.clearSelection()
      tableDom.value.toggleRowSelection(orderType, true)
      changeStatus(3)
    }
  }

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const route = useRoute()
  const loading = ref(false)
  const addDialog = ref(false)
  const name = ref('') // 名称

  const tableData = ref([]) // 列表数据
  const tableDom = ref<TableInstance | null>(null) // 列表dom

  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目

  const dialogTitle = ref('')
  const dialogLoading = ref(false)
  const formRef = ref<FormInstance>() // 表单元素

  // 表单数据
  const form = reactive({
    id: null,
    name: '',
    parentId: null,
    sort: 0,
    status: false,
  })

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    sort: [
      { required: false, message: '请输入分类排序', trigger: 'blur' },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
  })

  // 列表序号
  const indexMethod = (index: number) => {
    return index + 1
  }

  // 获取分页数据
  const getPageData = () => {
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
  }

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    await moduleTypeGetList(getPageData(), route.params.id).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 添加数据
  const addData = () => {
    addDialog.value = true
    dialogTitle.value = '添加分类'
    form.id = null
    form.name = ''
    form.parentId = null
    form.sort = 0
    form.status = false
  }

  // 保存方法
  const saveDataMethod = (method, data) => {
    dialogLoading.value = true
    method(data, route.params.id).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        addDialog.value = false
        dialogLoading.value = false
        getList()
      } else {
        ElMessage({
          message: res.data.message,
          type: 'warning',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        dialogLoading.value = false
        return
      }
    })
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        if (dialogTitle.value == '添加分类') {
          form.parentId = 0
        }
        if (dialogTitle.value == '编辑分类') {
          form.parentId = ''
        }
        if (dialogTitle.value == '添加下级') {
          form.parentId = form.id
          form.id = null
        }
        saveDataMethod(moduleTypeSave, form)
      }
    })
  }

  // 修改状态方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的分类`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确认${type}选中的分类?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
        })
      } else {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (dialog != '') {
            addDialog.value = false
          }
        })
      }
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeStatus = (n) => {
    if (n == 1) {
      changeMethod('启用', moduleTypeDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', moduleTypeDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', moduleTypeDelete, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeMethod('删除', moduleTypeDelete, [form.id], 3, addDialog)
    }
  }

  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
